<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/23
 * Time: 18:07
 */

namespace App\Process;

use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Component\Timer;
use EasySwoole\HttpClient\HttpClient;

class CsgoBet extends AbstractProcess
{
    public function run($arg)
    {
        go(function ()use($arg){
            Timer::getInstance()->loop(15000,function (){
                MysqlPool::invoke(function (MysqlObject $db){
                    $match_ids = $db->whereIn('status',[1])->getColumn('siam_csgomatchs','match_id');
                    foreach ( $match_ids as $match_id ){
                        list($s1, $s2) = explode(' ', microtime());
                        $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
                        $url = UrlEnums::FJURL.UrlEnums::CSGO_BET_PATH."?match_id={$match_id}&version=2";
                        $client = new HttpClient($url);
                        $option = [
                            'path'      => UrlEnums::CSGO_BET_PATH,
                            'api_time'  => $microtime
                        ];
                        $header = Auth::getInstance()->header($option);
                        $client->setHeaders($header,true,false);
                        $response = $client->get();
                        $content = $response->getBody();
                        $data = json_decode($content,true);
                        if( isset($data['code']) && $data['code'] == 200 && $data['data'] ){
                            foreach ( $data['data'] as $k=>$v ){
                                $v['options'] = json_encode($v['options']);
                                $res = $db->where('bet_id',$v['bet_id'])->getOne('siam_csgobet');
                                if( !$res ){
                                    $raw = $db->insert('siam_csgobet',$v);
                                }else{
                                    $raw = $db->where('bet_id',$v['bet_id'])->update('siam_csgobet',[
                                        'options' => $v['options'],
                                        'status'  => $v['status']
                                    ]);
                                }
                            }
                        }
                    }
                });
            });
        });
    }
}